//
//  EngController_finish.m
//  Estate
//
//  Created by heyong on 16/9/6.
//  Copyright © 2016年 ttsx. All rights reserved.
//

#import "EngController_finish.h"
#import "NewInspectionTextCell.h"
#import "LeaderInspMergeController.h"
#import "LeaderAddInspController.h"
#import "LeaderAuditController.h"

@interface EngController_finish (){
    FMDatabase *db;
    //一键汇总id
    NSString *_totalId;
}
@property (strong, nonatomic)UIButton *addBtn;

@end

@implementation EngController_finish
- (NSMutableArray *)dataArray1{
    if(_dataArray1==nil){
        _dataArray1=[NSMutableArray array];
    }
    return _dataArray1;
}

-(UITableView *)tableView{
    if(_tableView==nil){
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, (DEF_SCREEN_HEIGHT-84-35*BIZ))];
        _tableView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
        [LSUtility setExtraCellLineHidde:_tableView tabHeader:NO tabFooter:NO];
        [_tableView registerNib:[UINib nibWithNibName:@"NewInspectionTextCell" bundle:nil] forCellReuseIdentifier:@"detail"];
        _tableView.delegate=self;
        _tableView.dataSource=self;
    }
    return _tableView;
}



- (void)viewDidLoad {
    NSLog(@"已完成巡检任务id:%@",self.processId);
    [super viewDidLoad];
    [self.view addSubview: self.tableView];
    self.addBtn=[[UIButton alloc]initWithFrame:CGRECTS(260, 360, 100, 100)];
    [_addBtn setImage:[UIImage imageNamed:@"yijianbtn"] forState:UIControlStateNormal];
    [self.view addSubview:_addBtn];
    [self.addBtn addTarget:self action:@selector(addContent) forControlEvents:UIControlEventTouchUpInside];
    db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    
    [self initDataSource];
    
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(initDataSource) name:@"Refresh_xjzz" object:nil];
}

//初始化数据
- (void)initDataSource
{
    [self.dataArray1 removeAllObjects];
    [db open];
    //存储
    NSMutableArray *inspectArray=[NSMutableArray array];
    //存储当前巡检项和当前状态
    NSMutableDictionary *itemStateDic=[NSMutableDictionary dictionary];
    
    //用户巡检项为1  但是条数为2的
    NSString *sql_state_1=[NSString stringWithFormat:@"select * from INSPECT_USER_ITEM where inspect_process_id='%@' and inspect_current_state='1'",self.processId];
    FMResultSet *result_state_1=[db executeQuery:sql_state_1];
    
    while ([result_state_1 next]) {
        
        NSString *userItemId=[result_state_1 stringForColumn:@"id"];
        //先查询巡检条数 如果大于2那就巡检过  解决检查过 却没有更改在状态的bug
        NSString *sql_check=[NSString stringWithFormat:@"select id FROM INSPECT_PROCESS_RECORD where inspect_user_item_id='%@'",userItemId];
        NSMutableArray *checkArray=[NSMutableArray array];
        
        FMResultSet *result_check=[db executeQuery:sql_check];
        
        while ([result_check next]) {
            NSString *checkid=[result_check stringForColumn:@"ID"];
            [checkArray addObject:checkid];
        }
        if(checkArray.count>1){
            NSString *userItemId=[result_state_1 stringForColumn:@"id"];
            NSString *state=[result_state_1 stringForColumn:@"inspect_current_state"];
            [itemStateDic setObject:state forKey:userItemId];
            [inspectArray addObject:userItemId];
        }
    }
    
    
    //用户巡检项不为1的数据
    NSString *sql_0=[NSString stringWithFormat:@"select * from INSPECT_USER_ITEM where inspect_process_id='%@' and inspect_current_state!='1'",self.processId];
    FMResultSet *result_0=[db executeQuery:sql_0];
    
    
    while ([result_0 next]) {
        NSString *userItemId=[result_0 stringForColumn:@"id"];
        NSString *state=[result_0 stringForColumn:@"inspect_current_state"];
        [itemStateDic setObject:state forKey:userItemId];
        [inspectArray addObject:userItemId];
    }
    
    
    NSMutableArray *idsArr=[NSMutableArray array];
    for (NSString *key in [itemStateDic allKeys]) {
        NSString *state=itemStateDic[key];
        NSString *ids=[LSUtility quertinspectRecordStateByUserItemId:key AndState:state];
        [idsArr addObject:ids];
    }
    //作为条件
    NSString *inspectStr=[LSUtility dictionaryToJson_2:idsArr];
    //转化为sql条件
    NSString *inspectCon=[LSUtility SymbolConversion:inspectStr];
    
    NSString *sqlStr=[NSString stringWithFormat:@"select count(*) as count,CASE WHEN sontab.pname IS NULL THEN (SELECT INSPECT_NAME FROM inspect_item where id=ipr.INSPECT_ITEM_ID) ELSE sontab.pname  END as pname,ipr.* from INSPECT_PROCESS_RECORD as ipr,(select (select iison.inspect_name from INSPECT_ITEM as iison where iison.id=ii.parent_id limit 1) as pname,ID FROM INSPECT_ITEM as ii GROUP BY ii.ID) as sontab where sontab.id=ipr.inspect_item_id and ipr.id in %@ and ipr.INSPECT_PROCESS_ID='%@' GROUP BY CASE  WHEN sontab.pname IS NULL THEN (SELECT INSPECT_NAME FROM inspect_item where id=ipr.INSPECT_ITEM_ID) ELSE sontab.pname END ",inspectCon,self.processId];
    
    FMResultSet *result_1=[db executeQuery:sqlStr];
    //查询到分类
    NSMutableDictionary *dic;
    while ([result_1 next]) {
        //得到父类标题
        NSString *parentName=[result_1 stringForColumn:@"pname"];
        //得到分类条数
        NSString *count=[result_1 stringForColumn:@"count"];
        
        //得到巡检项id
        NSString *item_id=[result_1 stringForColumn:@"INSPECT_ITEM_ID"];
        
        //通过父类标题查询到下面的itemId  原始方法查询不到父级无
        NSString *sqlRecord=[NSString stringWithFormat:@"select CASE WHEN sontab.pname IS NULL THEN (SELECT INSPECT_NAME FROM inspect_item where id=ipr.INSPECT_ITEM_ID) ELSE sontab.pname  END as pname,ipr.* from INSPECT_PROCESS_RECORD as ipr,(select (select iison.inspect_name from INSPECT_ITEM as iison where iison.id=ii.parent_id limit 1) as pname,ID FROM INSPECT_ITEM as ii GROUP BY ii.ID) as sontab where sontab.id=ipr.inspect_item_id and ipr.inspect_item_id not in('') and ipr.id in %@  and ipr.INSPECT_PROCESS_ID='%@' and ipr.INSPECT_ITEM_STATE!='1'  and ( pname='%@' or pname ISNULL) ORDER BY(ipr.INSPECT_USER_ID)",inspectCon,self.processId,parentName];
        
        //查询实体表
        //        NSString *sqlRecord=[NSString stringWithFormat:@"select sontab.pname ,ipr.*  from INSPECT_PROCESS_RECORD as ipr,(select CASE WHEN (select iison.inspect_name from INSPECT_ITEM as iison where iison.id=ii.parent_id limit 1) IS NULL THEN(SELECT INSPECT_NAME FROM inspect_item where id='%@') ELSE (select iison.inspect_name from INSPECT_ITEM as iison where iison.id=ii.parent_id limit 1) END as pname,ID FROM INSPECT_ITEM as ii GROUP BY ii.ID) as sontab where sontab.id=ipr.inspect_item_id and ipr.inspect_item_id not in('') and ipr.id in %@  and ipr.INSPECT_PROCESS_ID='%@' and ( pname='%@' or pname ISNULL) ORDER BY(ipr.INSPECT_USER_ID)",item_id,inspectCon,self.processId,parentName];
        
        FMResultSet *result_2=[db executeQuery:sqlRecord];
        
        NSMutableArray *DetailArr=[NSMutableArray array];
        while ([result_2 next]) {
            //流程记录ID
            NSString *processId=[result_2 stringForColumn:@"ID"];
            NSString *pname=[result_2 stringForColumn:@"pname"];
            
            
            //查询出状态为2的 才能待汇总！！！ ids是汇总id!!!
            NSString *state2Id=[LSUtility queryInspectStateId:processId state:@"2"];
            //2没有 就查询5
            
            if(!state2Id){
                state2Id=[LSUtility queryInspectStateId:processId state:@"5"];
            }
            if(state2Id){
                //                NSLog(@"状态为2  为5 id为空");
            }
//            DeLog(@"pname:%@",pname);
            //只添加自己类所属下的数据
            if([pname isEqualToString:parentName]){
                NSDictionary *dics2=[result_2 resultDictionary];

                NSLog(@"%@",dics2);
                //itemID
                NSString *itemId=[result_2 stringForColumn:@"INSPECT_ITEM_ID"];
                //根据itemId 查询实体表
                NSString *sql_item= [NSString stringWithFormat:@"select * from INSPECT_ITEM where id='%@'",itemId];
                FMResultSet *result_3=[db executeQuery:sql_item];
                NSMutableDictionary *muDic;
                while ([result_3 next]) {
                    //根据巡检项id 得到流程ID
                    NSString *inuserId=[LSUtility getInspectUserName:processId];
                    NSString *name=[LSUtility getuserIdByUserName:inuserId][@"REAL_NAME"];
                    
                    NSDictionary *dics=[result_3 resultDictionary];
                    muDic=[NSMutableDictionary dictionaryWithDictionary:dics];
                    if(name){
                        [muDic setObject:name forKey:@"name"];
                        [muDic setObject:inuserId forKey:@"inspectUserId"];
                    }
                    
                    NSString *inspectItemId=[result_2 stringForColumn:@"INSPECT_ITEM_ID"];
                    NSString *userItemId=[result_2 stringForColumn:@"INSPECT_USER_ITEM_ID"];
                    NSString *inspectResult=[result_2 stringForColumn:@"INSPECT_RESULT"];
                    NSString *inspectItemInfo=dics[@"INSPECT_NAME"];
                    
                    [muDic setObject:inspectItemInfo forKey:@"inspectItemInfo"];
                    [muDic setObject:userItemId forKey:@"userItemId"];
                    [muDic setObject:inspectItemId forKey:@"inspectItemId"];
                    [muDic setObject:DEFISNUL(state2Id)  forKey:@"ids"];
                    [muDic setObject:inspectResult forKey:@"state"];
                    
                }
                
                //查询当前任务状态
                NSString *type=[result_2 stringForColumn:@"INSPECT_ITEM_STATE"];
                if([type isEqualToString:@"1"]){
                    type=@"待巡检";
                }else if ([type isEqualToString:@"2"]){
                    type=@"待汇总";
                }else if ([type isEqualToString:@"3"]){
                    type=@"待整改";
                }else if ([type isEqualToString:@"4"]){
                    type=@"待审阅";
                }else if ([type isEqualToString:@"5"]){
                    type=@"已完成";
                }
                //设置状态
                [muDic setObject:type forKey:@"type"];
                [DetailArr addObject:muDic];
                NSLog(@"%@",muDic);
            }
            
        }
        //存在数据
        if (DetailArr.count>0) {
            
            //设置标题
            NSString *title=[NSString stringWithFormat:@"%@  (%@条)",parentName,count];
            dic=[[NSMutableDictionary alloc] initWithObjectsAndKeys:DetailArr,DIC_ARARRY,title,DIC_TITILESTRING,[NSNumber numberWithInt:0],DIC_EXPANDED,nil];
            [self.dataArray1 addObject:dic];
        }
    }
    
    /*
     *  查询额外巡检
     */
    NSString *nullIUISql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_PROCESS_RECORD WHERE INSPECT_PROCESS_ID = '%@' AND INSPECT_ITEM_ID = '' and inspect_item_state!='1' group by INSPECT_USER_ITEM_ID  order by create_time desc", self.processId];
    FMResultSet *nullIUIResult = [db executeQuery:nullIUISql];
    NSMutableArray *secondArr2 = [NSMutableArray array];
    while ([nullIUIResult next]) {
        //巡检人姓名
        NSString *inuserId=[nullIUIResult stringForColumn:@"INSPECT_USER_ID"];
        NSString *name=[LSUtility getuserIdByUserName:inuserId][@"REAL_NAME"];
        // 用户巡检项ID
        NSString *inspectUserItemId = [nullIUIResult stringForColumn:@"INSPECT_USER_ITEM_ID"];
        //查询巡检用户表
        NSString *inspUItemStr = [NSString stringWithFormat:@"SELECT * FROM INSPECT_USER_ITEM WHERE id = '%@'", inspectUserItemId];
        FMResultSet *result_2 = [db executeQuery:inspUItemStr];
        // 额外巡检名称
        NSString *tionalName=@"";
        while ([result_2 next]) {
            tionalName=[result_2 stringForColumn:@"INSPECT_ADDTIONAL_NAME"];
        }
        //流程记录ID
        NSString *ids = [nullIUIResult stringForColumn:@"ID"];
        NSString *resultSta=[LSUtility getInspectStateByProcessRecordId:ids];
        
        //查询当前任务状态
        NSString *type=[nullIUIResult stringForColumn:@"INSPECT_ITEM_STATE"];
        if([type isEqualToString:@"1"]){
            type=@"待巡检";
        }else if ([type isEqualToString:@"2"]){
            type=@"待汇总";
        }else if ([type isEqualToString:@"3"]){
            type=@"待整改";
        }else if ([type isEqualToString:@"4"]){
            type=@"待审阅";
        }else if ([type isEqualToString:@"5"]){
            type=@"已完成";
        }
        
        if(!name){
            name=@"未知";
        }
        // 每条巡检项数据
        NSDictionary *rowDic = @{@"INSPECT_NAME":DEFISNUL(tionalName) ,@"ids":ids,@"name":name,@"state":resultSta,@"types":@"extra",@"type":type,@"userItemId":inspectUserItemId,@"inspectItemId":@"",@"inspectUserId":inuserId,@"inspectItemInfo":DEFISNUL(tionalName)};
        NSMutableDictionary *mudic=[NSMutableDictionary dictionaryWithDictionary:rowDic];
        [secondArr2 addObject:mudic];
    }
    
    if (secondArr2.count > 0) {
        // 每组任务数据
        NSString *title=[NSString stringWithFormat:@"其它  (%li条)",secondArr2.count];
        NSMutableDictionary *firstDic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:title, DIC_TITILESTRING, secondArr2, DIC_ARARRY, [NSNumber numberWithInt:0], DIC_EXPANDED, nil];
        // 将字典加入数组
        [self.dataArray1 addObject:firstDic];
    }
    
    //    if (!(self.dataArray1.count > 0)) {
    //        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 200*BIZ, DEF_SCREEN_WIDTH, 40*BIZ)];
    //        label.text = @"您没有以完成的任务!";
    //        label.textAlignment=1;
    //        label.font = [UIFont systemFontOfSize:24*BIZ];
    //        label.textColor=UIColorFromRGB(0x787878);
    //        [self.view addSubview:label];
    //    }
    
    [self.tableView reloadData];
    [db close];
}


#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray1.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSMutableDictionary *dic=[self.dataArray1 objectAtIndex:section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    //判断是收缩还是展开
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return array.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    long section=indexPath.section;
    long row=indexPath.row;
    
    //    得到改组下信息
    NSMutableDictionary *dic=[self.dataArray1 objectAtIndex:section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    NSDictionary *reDic=array[row];
    
    NewInspectionTextCell *cell=[NewInspectionTextCell cellWithTableView:tableView];
    NSString *names=@"未知";
    if(reDic[@"name"]||[reDic[@"name"] isEqualToString:@""]){
        names=reDic[@"name"];
    }
    cell.title.text=[NSString stringWithFormat:@"(%@)%@",names,[reDic objectForKey:@"INSPECT_NAME"]];
    cell.state.text=reDic[@"type"];
    return  cell;
}


//设置分组头的视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *hView = [[UIView alloc]initWithFrame:CGRectMake(0,0, DEF_SCREEN_WIDTH,(CELL_HEIGHT-5)*BIZ)];
    hView.backgroundColor=[UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1.00];
    UIButton* eButton = [[UIButton alloc] init];
    eButton.backgroundColor=[UIColor whiteColor];
    //按钮填充整个视图
    eButton.frame = hView.frame;
    [eButton addTarget:self action:@selector(expandButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    //把节号保存到按钮tag，以便传递到expandButtonClicked方法
    eButton.tag = section;
    //根据是否展开，切换按钮显示图片
    if ([self isExpanded:section])
        [eButton setImage:  [UIImage imageNamed: @"xiala" ]forState:UIControlStateNormal];
    else
        [eButton setImage: [UIImage imageNamed: @"gengduo1" ]forState:UIControlStateNormal];
    
    //设置分组标题
    [eButton setTitle:[[self.dataArray1 objectAtIndex:section] objectForKey:DIC_TITILESTRING]forState:UIControlStateNormal];
    
    [eButton setTitleColor:[UIColor colorWithRed:0.68 green:0.68 blue:0.68 alpha:1.00] forState:UIControlStateNormal];
    //设置字体样式
    eButton.titleLabel.font=[UIFont systemFontOfSize:16.*BIZ];
    
    //设置button的图片和标题的相对位置
    
    //4个参数是到上边界，左边界，下边界，右边界的距离
    eButton.contentHorizontalAlignment =UIControlContentHorizontalAlignmentLeft;
    UIImage *image=eButton.imageView.image;
    [eButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, image.size.width)];
    [eButton setImageEdgeInsets:UIEdgeInsetsMake(0, eButton.titleLabel.bounds.size.width+20, 0, -eButton.titleLabel.bounds.size.width)];
    //添加btn
    [hView addSubview: eButton];
    return hView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    //判断是收缩还是展开
    NSMutableDictionary *dic=[self.dataArray1 objectAtIndex:section];
    if ([[dic objectForKey:DIC_EXPANDED]intValue]) {
        return 5;
    }else{
        return 0.1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dic=[self.dataArray1 objectAtIndex:indexPath.section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    NSDictionary *reDic=array[indexPath.row];
    return [self cellHeightWithObj:[NSString stringWithFormat:@"(%@)%@",reDic[@"name"],[reDic objectForKey:@"INSPECT_NAME"]]];;
}


- (CGFloat)cellHeightWithObj:(NSString *)string{
    CGFloat cellHeight = 60;
    CGFloat mWidth = [UIScreen mainScreen].bounds.size.width - 100;
    cellHeight = [string boundingRectWithSize:CGSizeMake(mWidth,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin  attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:17*BIZ]} context:nil].size.height;
    if(cellHeight<=60){
        return 60;
    }else{
        return cellHeight;
    }
}



//控制表头分组表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 46*BIZ;
}

#pragma mark-点击表格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //得到改组下信息
    NSMutableDictionary *dic=[self.dataArray1 objectAtIndex:indexPath.section];
    NSArray *array=[dic objectForKey:DIC_ARARRY];
    NSDictionary *dics=array[indexPath.row];
    
    NSString *state=dics[@"type"];
    if([state isEqualToString:@"待审阅"]||[state isEqualToString:@"已完成"]){
        LeaderAuditController *leader=[[LeaderAuditController alloc]init];
        leader.recordId=dics[@"ids"];
        leader.ipqc=dics[@"types"];
        leader.flag=@"query";
        [self.navigationController pushViewController:leader animated:YES];
        
    }else{
        //跳转详情
        LeaderAddInspController *leaderVC=[[LeaderAddInspController alloc]init];
        //巡检记录id
        leaderVC.prosessId=dics[@"ids"];
        //例行巡礼 和额外巡检
        leaderVC.ipqc=dics[@"types"];
        //任务id
        leaderVC.taskId=self.processId;
        leaderVC.inspectUserId=dics[@"inspectUserId"];
        //查看是否一键汇总能否编辑
        leaderVC.flag=@"mod";
        [self.navigationController pushViewController:leaderVC animated:YES];
    }
    
}

#pragma mark-一键合并
- (void)addContent{
    //查询该流程下是否还有未检查项（是、不允许合并）
    NSString *sql_1=[NSString stringWithFormat:@"select count(1) as count from INSPECT_PROCESS_RECORD where INSPECT_PROCESS_ID='%@'  AND inspect_item_id !='' group by INSPECT_USER_ITEM_ID",self.processId];
    [db open];
    FMResultSet *result_1 = [db executeQuery:sql_1];
    int counts=0;
    while ([result_1 next]) {
        int count=[result_1 intForColumn:@"count"];
        if(count<=1){
            counts=1;
            break;
        }
    }
    [db close];
    
    if(counts==1){
        [LSUtility showToastWithMessage:@"请先完成待办中的巡检项！" inView:self.tableView Andtime:1.8];
    }else{
        //判断是否流转到下一阶段 流转后不能编辑
        BOOL isquery=[LSUtility getProcessZongjianState4:self.processId];
        if(isquery){
            [self jumpHuiZong:NO flag:@""];
        }else{
            //查询是否已经合并（是、查看操作）
            NSArray *totalArr= [LSUtility getTotalByProcessID:self.processId];
            //得到一键汇总后的id
            _totalId=[totalArr lastObject][@"ID"];
            //是否同步 同步后不能编辑
            BOOL  istong=[LSUtility getTotalRecordEditById:_totalId];
            if(totalArr.count>0){
                if(istong){
                    [self jumpHuiZong:NO flag:@""];
                }else{
                    [self alertShow:@"你已经汇总过，是否重置汇总？"];
                }
            }else{
                [self jumpHuiZong:YES flag:@""];
            }
        }
    }
}

- (void)jumpHuiZong:(BOOL)isOk flag:(NSString *)flag{
    LeaderInspMergeController *leaderVC=[[LeaderInspMergeController alloc]init];
    if(isOk){
        NSMutableArray *totalArr=[NSMutableArray array];
        //移除不涉及的id
        for (int i=0;i<self.dataArray1.count;i++) {
            NSDictionary *dict=self.dataArray1[i];
            NSMutableArray *arr=[dict objectForKey:@"array"];
            @try {
                NSMutableArray *totalArr2=[NSMutableArray array];
                for (int j=0; j<arr.count; j++) {
                    NSDictionary *dic=arr[j];
                    if([dic[@"state"] isEqualToString:@"2"]){
                        //不涉及不进行一键汇总
                    }else{
                        [totalArr2 addObject:dic];
                        //NSLog(@"传入ids：%@",dic[@"ids"]);
                    }
                }
                NSString *title=dict[@"title"];
                NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:totalArr2,@"array",title,@"title", nil];
                
                [totalArr addObject:dic];
                
            } @catch (NSException *exception) {
                NSLog(@"error:%@",exception);
            } @finally {
            }
            
        }
        
        //移除为0的分组
        for (int i=0;i<totalArr.count;i++) {
            NSDictionary *dict=self.dataArray1[i];
            NSMutableArray *arr=[dict objectForKey:@"array"];
            if (arr.count==0) {
                [totalArr removeObject:dict];
            }
        }
        
        //数据传递给一键汇总页面
        leaderVC.dataArray=nil;
        leaderVC.dataArray=[NSMutableArray arrayWithArray:totalArr];
        leaderVC.totalId=_totalId;
        leaderVC.isEdit=YES;
        
    }else{
        leaderVC.isEdit=NO;
    }
    
    //传递巡检任务
    leaderVC.processId=self.processId;
    //重置标识
    leaderVC.flag=flag;
    //传入用户巡检项id
    
    [self.navigationController pushViewController:leaderVC animated:YES];
}

#pragma mark -- 内部调用
//对指定的节进行“展开/折叠”操作,若原来是折叠的则展开，若原来是展开的则折叠
-(void)collapseOrExpand:(long)section{
    NSMutableDictionary *dic=[self.dataArray1 objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    if (expanded) {
        [dic setValue:[NSNumber numberWithInt:0]forKey:DIC_EXPANDED];
    }else
    {
        [dic setValue:[NSNumber numberWithInt:1]forKey:DIC_EXPANDED];
    }
}

//返回指定节是否是展开的

-(int)isExpanded:(long)section{
    NSDictionary *dic=[self.dataArray1 objectAtIndex:section];
    int expanded=[[dic objectForKey:DIC_EXPANDED] intValue];
    return expanded;
}

//按钮被点击时触发
-(void)expandButtonClicked:(id)sender{
    UIButton* btn= (UIButton*)sender;
    long section= btn.tag;//取得tag知道点击对应哪个块
    [self collapseOrExpand:section];
    //刷新tableview
    [self.tableView reloadData];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark--提示语
- (void)alertShow:(NSString *)str{
    UIAlertController *altCor=[UIAlertController alertControllerWithTitle:@"提示" message:str preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self jumpHuiZong:YES flag:@"up"];
    }];
    
    UIAlertAction *cancel=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self jumpHuiZong:NO flag:@""];
    }];
    
    [altCor addAction:action];
    [altCor addAction:cancel];
    [self presentViewController:altCor animated:YES completion:nil];
}

@end
